const express = require('express');
const router = express.Router()
const pool = require('./pool')
const crypto = require('crypto')

// console.log('pool=',pool)

module.exports = router

// 注册
router.post('/zhuc', (req, res, next) => {
  let user_name = req.query.user_name
  let email = req.query.email
  let uphone = req.query.uphone
  let pass_word = hx256(req.query.pass_word)
  let random = req.query.ran
  // console.log('name=', user_name)
  // console.log('password=', pass_word)
//使用哈希256进行加密
  

  // 判空
  if (user_name == '' || pass_word == '') {
    res.send({code:400,msg:'账号密码不能为空'})
    return ''
  }

  let sql = "insert into lh_user set user=?,uemail=?,uphone=?,pwd=?,random=?"
  pool.query(sql, [user_name, email, uphone, pass_word, random], (err, result) => {
    if (err) {
      return next(err)
    }
    if (result.affectedRows === 0) {
      res.send({ code: 501, msg: '注册失败' })
    } else {

      res.send({ code: 200, msg: '成功', data: { 'username': user_name, 'email': email, 'phone': uphone, 'password': pass_word, 'random': random } })
    }

  })
})
// 哈希256  函数
function hx256(hxe){
  let sha256 = crypto.createHash('sha256').update(hxe).digest('hex')
  return sha256
}

//  判断 用户名是否注册过
router.get('/xun',(req,res,next)=>{
  let user_name = req.query.user_name
  // console.log('user_name=', user_name)

	let sql = 'select user from lh_user where user=?'
	pool.query(sql,[user_name],(err,result)=>{
    if (err) {
      return next(err)
    }
    // console.log('result=',result)
    // console.log('result[0]== ',result[0])
    if(result[0] )  {
    // console.log('result[0].user == ',result[0].user) // 取得的数据
      res.send({ code: 200, msg: '已注册' })
    }else{
      res.send({ code: 500, msg: '未注册', })
    }
  })

})
// //  login 登录
// router.get('/login', (req, res) => {
//   let user_name = req.query.user_name
//   let pass_word = req.query.pass_word

//   	// 根据账号密码查询数据库  获取数据库对应的，头像码
// 	let sql = 'select random from lh_user where user=? and pwd=?'
// 	pool.query(sql,[user_name,pass_word],(err,result)=>{
// 		if(err){
// 			return next(err)
// 		}
// 		console.log('re1',result)
// 		if(result.length>0){
// 			res.send({code:200,msg:'select success 成功',data:result})			
// 		}else{
// 			res.send({code:500,msg:'失败',data:result})
// 		}		
// 	})

// });


//
// router.post('/add', (req, res, next) => {
//   let user = req.body.user
//   let uemail = req.body.uemail
//   let uphone = req.body.uphone
//   let pwd = req.body.pwd
//   let random = req.body.random

//   let sql = 'insert into lh_user set user=?,uemail=?,uphone=?,pwd=?,random=?'

//   pool.query(sql, [user, uemail, uphone, pwd, random], (err, result) => {
//     if (err) {
//       return next(err)
//     }

//     if (result.affectedRows === 0) {
//       res.send({ code: 501, msg: '注册失败' })
//     } else {
//       res.send({ code: 200, msg: '注册成功' })
//     }

//   })
// })